<template>
  <a-modal :width="900" title="新增优惠券" :after-close="reset" @ok="submit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '120px' } }">
      <a-form-item label="优惠券名称" name="name">
        <a-input v-model:value="form.name" placeholder="优惠券名称" />
      </a-form-item>
      <a-form-item label="优惠劵类型" name="useType">
        <a-radio-group v-model:value="form.useType">
          <a-radio :value="1"> 通用券</a-radio>
          <a-radio :value="2">商品券 </a-radio>
          <a-radio :value="3">品类券 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.useType === 3" label="选择品类：" name="primaryKey">
        <a-cascader v-model:value="form.primaryKey" :options="merCateList"
          :field-names="{ label: 'name', value: 'id', children: 'child' }" clearable class="selWidth"
          :show-all-levels="false" />
      </a-form-item>
      <!-- <a-form-item v-if="form.useType === 2" label="商品：" name="primaryKey">
        <a-select v-model:value="form.checked" clearable>
          <a-select-option v-for="item in SHOW_OPTION" :key="item.value" :value="item.value">
            {{ item.value }}
          </a-select-option>
        </a-select>
      </a-form-item> -->
      <a-form-item label="优惠券面值" name="money">
        <a-input-number v-model:value="form.money" :min="1" placeholder="兑换的优惠券面值" />
      </a-form-item>
      <a-form-item label="使用门槛" name="threshold">
        <a-radio-group v-model:value="threshold">
          <a-radio :value="false"> 无门槛</a-radio>
          <a-radio :value="true">有门槛 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="threshold" label="优惠券最低消费" name="minPrice">
        <a-input-number v-model:value="form.minPrice" :min="1" />
      </a-form-item>
      <a-form-item label="使用有效期" name="threshold">
        <a-radio-group v-model:value="form.isFixedTime">
          <a-radio :value="false"> 天数</a-radio>
          <a-radio :value="true">时间段 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="!form.isFixedTime" label="使用有效期限（天）" name="day">
        <a-input-number v-model:value="form.day" :min="1" />
      </a-form-item>
      <a-form-item v-if="form.isFixedTime" label="使用有效期限" name="day">
        <a-range-picker v-model:value="timeVal" value-format="YYYY-MM-DD 00:00:00" />
      </a-form-item>
      <a-form-item label="领取是否限时" name="isForever">
        <a-radio-group v-model:value="form.isForever">
          <a-radio :value="true"> 限时</a-radio>
          <a-radio :value="false">不限时 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item v-if="form.isForever" label="领取时间" name="day">
        <a-range-picker v-model:value="isForeverTime" value-format="YYYY-MM-DD 00:00:00" />
      </a-form-item>
      <a-form-item label="领取方式" name="resource">
        <a-radio-group v-model:value="form.type">
          <a-radio :value="1"> 手动领取</a-radio>
          <a-radio :value="2">新人券 </a-radio>
          <a-radio :value="3">赠送券</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="是否限量" name="isLimited">
        <a-radio-group v-model:value="form.isLimited">
          <a-radio :value="true"> 限量</a-radio>
          <a-radio :value="false">不限量 </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="发放总数" name="total">
        <a-input-number v-model:value="form.total" :min="1" placeholder="发放总数" />
      </a-form-item>
      <a-form-item label="排序" name="sort">
        <a-input-number v-model:value="form.sort" :min="0" placeholder="排序" />
      </a-form-item>
      <a-form-item label="状态" name="status">
        <a-radio-group v-model:value="form.status">
          <a-radio :value="true"> 开启</a-radio>
          <a-radio :value="false">关闭 </a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { categoryApi } from '@/views/store/api';
import { storecouponAddup, storecouponinfo } from './api';
import { storecoupon, type Istorecoupon } from './entity';
import { validReg } from '@/utils/validate';

const props = withDefaults(defineProps<{
  data: Partial<Istorecoupon>
}>(), {
})

const { formRef, submit, close } = useDialog({ validCallback: save })
let threshold = $ref(false)
let timeVal = $ref<string[]>(["", ""]);
let isForeverTime = $ref<string[]>(["", ""])
let merCateList = $ref([{ id: '', name: '' }]);
let form = $ref(new storecoupon())
watchEffect(() => {
  if (props.data.id) {
    storecouponinfo(props.data.id).then(res => {
      let { coupon, product } = res
      form.setProps(coupon)
      form.checked = product || []
      threshold = coupon.minPrice == 0
      isForeverTime = coupon.isForever ? [coupon.receiveStartTime, coupon.receiveEndTime] : []
      timeVal = coupon.isFixedTime && coupon.useStartTime && coupon.useEndTime ? [coupon.useStartTime, coupon.useEndTime] : []
    })
  }
})

const rules = {
  storecouponName: [validReg('required', '请输入用户名')]
}
async function getCategorySelect() {
  let res = await categoryApi({ status: -1, type: 1 })

  let newArr = [];
  res.forEach((value: any, index: number) => {
    newArr[index] = value;
    if (value.child) newArr[index].child = value.child.filter(item => item.status === true)
  }) //过滤商品分类设置为隐藏的子分类不出现在树形列表里
  merCateList = newArr
}
onMounted(() => {
  getCategorySelect()
})
const emit = defineEmits(['change'])
function save() {
  if ((form.isFixedTime && !timeVal) || form.isFixedTime && !timeVal.length) return AntMessage.warning("请选择使用有效期限")
  if ((form.isForever && !isForeverTime) || (form.isForever && !isForeverTime.length)) return AntMessage.warning("请选择请选择领取时间")
  if (form.useType === 2) form.primaryKey = form.checked.map(item => { return item.id }).join(',')
  if (form.useType === 1) form.primaryKey = ''
  if (!threshold) form.minPrice = 0
  if (!form.isLimited) form.total = 0
  form.isFixedTime && timeVal.length ? (form.useStartTime = timeVal[0], form.day = '') : form.useStartTime = ''
  form.isFixedTime && timeVal.length ? (form.useEndTime = timeVal[1], form.day = '') : form.useEndTime = ''
  form.isForever && isForeverTime.length ? form.receiveStartTime = isForeverTime[0] : form.receiveStartTime = ''
  form.isForever && isForeverTime.length ? form.receiveEndTime = isForeverTime[1] : form.receiveEndTime = ''

  storecouponAddup(form).then(() => {
    AntMessage.success('新增成功')
    close()
    emit('change')
  })
}

function reset() {
  form = new storecoupon()
}
</script>

<style lang="less"></style>